package com.elontian.client;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.elontian.application.CodeBoyApplicationInfo;
import com.elontian.cache.CacheFactory;
import com.elontian.cache.CacheFileSuper;
import com.elontian.util.BitMapUtil;
import com.elontian.util.CheckUtil;

public final class BitMapCacheHelper {

	private static final CacheFileSuper<Bitmap, byte[]> cfs = CacheFactory
			.newCacheFileImg();;

	// 写入文件

	public static void writeBitmap(String url, Bitmap bitmap) {
		// TODO Auto-generated method stub
		cfs.write(url, bitmap);
	}

	// 读取资源中图片
	public static Bitmap readBitmapResource(Resources res, int resId,
			int outWidth, int outHeight) {
		InputStream is = null;
		try {
			is = res.openRawResource(resId);
			return BitMapUtil.setBitmapOption(BitMapUtil.getBytes(is),
					outWidth, outHeight);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	// 读取网络图片
	public static Bitmap readBitmapNet(String imageUrl, int outWidth,
			int outHeight) {
		InputStream is = null;
		try {
			URL myFileUrl = new URL(imageUrl);
			HttpURLConnection conn;
			conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			is = conn.getInputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			return BitMapUtil.setBitmapOption(BitMapUtil.getBytes(is),
					outWidth, outHeight);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	public static Bitmap readBitmapFromLocal(String imageUrl, int outWidth,
			int outHeight) {
		byte[] bitmapByte = cfs.read(imageUrl);
		Bitmap bitmap = null;
		try {
			if (bitmapByte != null && bitmapByte.length != 0) {
				bitmap = BitMapUtil.setBitmapOption(bitmapByte, outWidth,
						outHeight);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

	public static void setBitmapResource(ImageView view, int resId,
			int outWidth, int outHeight) {

		Bitmap bitmap = BitMapCacheHelper.readBitmapResource(
				CodeBoyApplicationInfo.appContext.getResources(), resId,
				outWidth, outHeight);

		if (CheckUtil.isNotNullBitmap(bitmap)) {
			view.setImageBitmap(bitmap);
		}
	}

}
